// 使用 api.ts 中的 request 函数
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000/api'

// 通用请求函数
async function request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
  const url = `${API_BASE_URL}${endpoint}`
  
  const config: RequestInit = {
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
    ...options,
  }

  // 添加认证token - 使用新的标签页隔离token系统
  let token: string | null = null
  
  try {
    // 首先尝试从新的标签页隔离系统获取token
    if (typeof window !== 'undefined') {
      // 动态导入缓存模块以避免SSR问题
      const { getTabToken, hasValidTabTokenEnhanced } = await import('@/lib/cache')
      
      if (hasValidTabTokenEnhanced()) {
        token = getTabToken()
        console.log('🔐 从标签页隔离系统获取到token')
      } else {
        // 降级到旧的localStorage方式
        token = localStorage.getItem('admin_token')
        console.log('🔐 从localStorage获取到token')
      }
    }
    
    if (token && token.trim() !== '' && token !== '无' && token !== '无...' && token.length >= 5) {
      config.headers = {
        ...config.headers,
        'Authorization': `Bearer ${token}`
      }
    } else {
      // 如果没有有效token，抛出明确的错误
      throw new Error('访问令牌缺失')
    }
  } catch (error) {
    console.error('❌ Token获取失败:', error)
    throw new Error('访问令牌缺失')
  }

  try {
    const response = await fetch(url, config)
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}))
      throw new Error(errorData.error || errorData.message || `HTTP error! status: ${response.status}`)
    }

    const data = await response.json()
    return data
  } catch (error) {
    console.error('API request failed:', error)
    throw error
  }
}

export interface MenuItem {
  key: string;
  label: string;
  icon?: string;
  path?: string;
  canEdit?: boolean;
  canDelete?: boolean;
  children?: MenuItem[];
}

export interface UserMenuResponse {
  code: number;
  message: string;
  data: {
    userRole: string;
    menus: MenuItem[];
  };
}

export interface RolePermission {
  menuKey: string;
  menuLabel: string;
  canView: boolean;
  canEdit: boolean;
  canDelete: boolean;
}

export interface RolePermissionsResponse {
  code: number;
  message: string;
  data: Record<string, RolePermission[]>;
}

export class MenuService {
  /**
   * 获取当前用户的菜单配置
   */
  static async getUserMenu(): Promise<UserMenuResponse> {
    const response = await request<UserMenuResponse>('/menu/user-menu');
    return response;
  }

  /**
   * 获取所有菜单配置（管理员专用）
   */
  static async getAllMenus(): Promise<any> {
    const response = await request<any>('/menu/all');
    return response;
  }

  /**
   * 获取角色权限配置（管理员专用）
   */
  static async getRolePermissions(): Promise<RolePermissionsResponse> {
    const response = await request<RolePermissionsResponse>('/menu/role-permissions');
    return response;
  }

  /**
   * 根据用户角色过滤菜单
   */
  static filterMenusByRole(menus: MenuItem[], userRole: string): MenuItem[] {
    // 这里可以根据角色进行额外的过滤逻辑
    return menus;
  }

  /**
   * 检查用户是否有权限访问某个菜单
   */
  static hasMenuPermission(menu: MenuItem, permission: 'view' | 'edit' | 'delete'): boolean {
    switch (permission) {
      case 'view':
        return true; // 如果能获取到菜单，说明有查看权限
      case 'edit':
        return menu.canEdit || false;
      case 'delete':
        return menu.canDelete || false;
      default:
        return false;
    }
  }
}
